package com.zhongkun.datahome.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhongkun.datahome.common.core.domain.entity.Tenant;
import com.zhongkun.datahome.common.core.domain.entity.TenantUser;
import com.zhongkun.datahome.common.enums.TenantUserStatusEnum;
import com.zhongkun.datahome.common.exception.ServiceException;
import com.zhongkun.datahome.common.utils.SecurityUtils;
import com.zhongkun.datahome.core.mapper.TenantMapper;
import com.zhongkun.datahome.core.mapper.TenantUserMapper;
import com.zhongkun.datahome.core.req.cmd.user.TenantUserCmd;
import com.zhongkun.datahome.core.service.ISysUserService;
import com.zhongkun.datahome.core.service.ITenantUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户用户Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-14
 */
@Service
public class TenantUserServiceImpl implements ITenantUserService {
    @Autowired
    private TenantUserMapper tenantUserMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private ISysUserService sysUserService;


    @Override
    public List<TenantUser> selectTenantUserByUserId(Long userId) {
        return tenantUserMapper.selectList(new LambdaQueryWrapper<TenantUser>().eq(TenantUser::getUserId, userId).orderByAsc(TenantUser::getId));
    }

    @Override
    public List<Tenant> queryTenantList(Long userId) {
        List<TenantUser> tenantUserList = selectTenantUserByUserId(userId);
        List<Long> tenantIdList = tenantUserList.stream().map(TenantUser::getTenantId).collect(Collectors.toList());

        return tenantMapper.selectList(new LambdaQueryWrapper<Tenant>().in(Tenant::getId, tenantIdList));
    }

    @Override
    public TenantUser getTenantUser(Long tenantId, Long userId) {
        List<TenantUser> tenantUserList = tenantUserMapper.selectList(new LambdaQueryWrapper<TenantUser>().eq(TenantUser::getUserId, userId).eq(TenantUser::getTenantId, tenantId));
        if (CollectionUtils.isNotEmpty(tenantUserList)) {
            return tenantUserList.get(0);
        }
        return null;
    }

    @Override
    public int updateUserStatus(TenantUserCmd user) {
        if (!TenantUserStatusEnum.isValid(user.getStatus())) {
            throw new ServiceException("商户用户状态无效");
        }

        TenantUser tenantUser = getTenantUser(SecurityUtils.getTenantId(), user.getUserId());
        if (tenantUser == null) {
            throw new ServiceException("当前商户下用户不存在");
        }

        // 删除商户下的token
        sysUserService.deleteTokenUserById(user.getUserId());
        tenantUser.setStatus(user.getStatus());
        return tenantUserMapper.updateById(tenantUser);
    }
}
